#include "StdAfx.h"
#include "DataPkt.h"

#define DP_STX    0xA5

UINT8 DataPkt::m_MsgId(0);

DataPkt::DataPkt(void)
:m_DevSn("sn1234")
{
	m_BufInit = true;
	m_Buf.resize(sizeof(DataPktReq) - 1, '0');
}

DataPkt::~DataPkt(void)
{
}

UINT8 DataPkt::ChkSum(UINT8 *data, UINT32 size)
{
    UINT8 sum = 0;
    
	while (size --)
	{
        sum += *data;
		data ++;
	}

	return sum;
}

void DataPkt::DevInfoSet(const char *DevSn, UINT8 DevId, UINT8 DevType)
{
	m_DevSn = DevSn;
	m_DevId = DevId;
	m_DevType = DevType;
}

void DataPkt::BufReset()
{
    m_BufInit = true;
}

bool DataPkt::ItemAdd(const char *str)
{
	if (m_BufInit)
	{
		m_Buf.resize(sizeof(DataPktReq) - 1, '0');
        m_Buf += m_DevSn;
        m_BufInit = false;
	}

	m_Buf += ",";
	m_Buf += str;

    return true;
}

bool DataPkt::WorkerCheckRsp(UINT8 *buf, UINT size, DpRspWrkChk &rsp)
{
    DataPktRsp *dp;
    
	if (buf == NULL || size < (sizeof(DataPktRsp) + 4))
		return false;
    
	dp = (DataPktRsp*)buf;

	if (dp->Stx != DP_STX)
		return false;

	if (dp->Cmd != DPCMD_WORKER_CHK)
		return false;

	rsp.Sorting = dp->Data[0] - '0';
	rsp.Weight = dp->Data[1] - '0';
	rsp.Check = dp->Data[2] - '0';

    return true;
}

UINT8* DataPkt::WorkerCheckReq(DpWorkers &w, UINT &size)
{
    ItemAdd(w.Sorting.Number.data());
    ItemAdd(w.Weight.Number.data());
    ItemAdd(w.Check.Number.data());

	ItemAdd(w.Sorting.Name.data());
	ItemAdd(w.Weight.Name.data());
	ItemAdd(w.Check.Name.data());

	return ReqMake(DPCMD_WORKER_CHK, &size);
}

UINT8* DataPkt::ReqMake(UINT8 cmd, UINT *size)
{
    DataPktReq *req;
	
    UINT len;

	req = (DataPktReq*)m_Buf.data();
    len = (UINT)m_Buf.size();
	if (size != NULL)
	{
	    *size = len;	
	}

	req->Stx = 0xA5;
	req->DevId = m_DevId;
	req->Cmd = cmd;
	req->DevType = m_DevType;
	req->MsgId = m_MsgId ++;
	req->DSize = len - sizeof(*req) + 1;
	req->NeedAck = 1;
	req->NeedData = 1;
	req->Stat = ChkSum(req->Data, req->DSize);

	printf("Size %d, Data %s\n", len, req->Data);

	return (UINT8*)req;
}